import { Component, Prop, Vue, Emit, Watch } from 'vue-property-decorator'
import { State, Mutation } from 'vuex-class'
import { RootState } from '@/store'

import styles from './ApplyInvoice.less'
import payOrder from '@/lib/request/payOrder'
import service from '@/lib/service'

const invoice = {
  notInvoice: 0, // 不需要
  invoicing: 1, // 未开票
  invoiced: 2, // 已开票
}
@Component({})
export default class ApplyInvoice extends Vue {
  @State((state: RootState) => state.user.accountEmail)
  private email!: string
  @State((state: RootState) => state.user.accountMobile)
  private accountMobile!: string
  @Mutation('user/setStateData') private setStateData!: any

  @Prop({ default: false }) private visible!: boolean
  @Prop({ default: () => {} }) private defaultData!: any

  private invoiceType: number = 1
  // private payOrderId: number = 0;
  private payerEmail: string = ''
  private taxpayerIdentityNumber: string = ''
  // 是否需要显示验证邮箱功能
  private verifySaveEmail: boolean = false
  // 手机验证码
  private verifySaveCode: string = ''
  // 按钮文字
  private verifyBtnMsg: string = '获取验证码'
  private timer: any = null

  // private invoiceTypeRadio = {
  // 	1: '电子发票',
  // 	2: '纸质发票',
  // }

  protected render(h: any) {
    return (
      <el-dialog
        class={styles.applyInvoice}
        title={
          this.defaultData.invoiceStatus === invoice.invoiced
            ? '开票详情'
            : '申请开票'
        }
        custom-class="custom-dialog"
        visible={this.visible}
        width="620px"
        before-close={this.beforeClose}
      >
        <el-form ref="form" label-width="80px">
          {/* <el-form-item label="商品名称">
            天印电子签章软件
          </el-form-item> */}

          <el-form-item label="发票金额">
            {this.defaultData.payAmount} 元
          </el-form-item>
          <el-form-item label="发票类型">增值税普票</el-form-item>
          <el-form-item label="发票介质">
            <el-radio-group v-model={this.invoiceType} disabled>
              <el-radio label={1}>
                电子发票
                <span> </span>
                <el-tooltip effect="dark" placement="bottom">
                  <div class={styles.tipContent} slot="content">
                    尊敬的用户您好，为响应国家推行电子发票的号召并确保发票开具时效，自2019年5月20日起，天谷信息科技有限公司将在全国范围内启用电子发票。
                    电子发票支持报销入账，其法律效力、基本用途及使用规定与增值税普通纸质发票一致。
                    相关法律规定：【国家税务局公告2015年第84号】国家税务总局关于推行通过增值税电子发票系统开具的增值税电子普通发票有关问题的公告。
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="付款名称">{this.defaultData.payer}</el-form-item>
          <el-form-item
            class="el-form-item-max el-form-item-two"
            label="付款方统一社会信用代码/纳税人识别号"
          >
            {this.defaultData.invoiceStatus === invoice.invoiced ? (
              this.taxpayerIdentityNumber
            ) : (
              <el-input
                v-model={this.taxpayerIdentityNumber}
                placeholder="请输入付款方统一社会信用代码/纳税人识别号"
              />
            )}
          </el-form-item>
          <el-form-item class="el-form-item-max" label="接收人电子邮箱">
            {this.defaultData.invoiceStatus === invoice.invoiced ? (
              this.payerEmail
            ) : (
              <div class="user-email-box">
                <el-input
                  v-model={this.payerEmail}
                  placeholder="请输入接收人电子邮箱"
                />

                {!this.email && (
                  <el-checkbox v-model={this.verifySaveEmail}>
                    保存邮箱
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="勾选后会保存到您的个人中心"
                      placement="bottom-end"
                    >
                      <i class="el-icon-question" />
                    </el-tooltip>
                  </el-checkbox>
                )}
              </div>
            )}
          </el-form-item>

          {this.verifySaveEmail && (
            <el-form-item class="el-form-item-max" label="手机号">
              <el-input v-model={this.accountMobile} disabled />
            </el-form-item>
          )}
          {this.verifySaveEmail && (
            <el-form-item
              class="el-form-item-max verify-code-box"
              label="手机验证码"
            >
              <el-input
                maxlength="6"
                v-model={this.verifySaveCode}
                placeholder="请输入验证码"
              />
              <el-button
                onClick={this.sendVerifyCode}
                disabled={this.verifyBtnMsg !== '获取验证码'}
                loading={this.verifyBtnMsg === '请求中'}
              >
                {this.verifyBtnMsg}
              </el-button>
            </el-form-item>
          )}
        </el-form>
        <span slot="footer" class="dialog-footer">
          {this.defaultData.invoiceStatus === invoice.invoiced && (
            <span class={styles.tips}>如需更改，请联系客服400-087-8198</span>
          )}
          <el-button
            onClick={() => {
              this.beforeClose()
            }}
          >
            {this.defaultData.invoiceStatus === invoice.invoicing
              ? '取消'
              : '关闭'}
          </el-button>
          {this.defaultData.invoiceStatus === invoice.invoicing && (
            <el-button
              type="primary"
              class="medium bg-color-blue"
              onClick={this.submit}
            >
              确认提交
            </el-button>
          )}
        </span>
      </el-dialog>
    )
  }

  private submit() {
    const RE_EMAIL = /[a-zA-Z0-9]{1,10}@[a-zA-Z0-9\\-]{1,50}\.[a-zA-Z0-9]{1,5}/
    this.taxpayerIdentityNumber = (this.taxpayerIdentityNumber || '').trim()
    this.payerEmail = (this.payerEmail || '').trim()
    if (!this.taxpayerIdentityNumber) {
      this.$message.error('请输入付款方统一社会信用代码/纳税人识别号')

      return
    }

    if (!this.payerEmail) {
      this.$message.error('请输入接收人电子邮箱')

      return
    } else if (!RE_EMAIL.test(this.payerEmail)) {
      this.$message.error('请输入正确的接收人电子邮箱')

      return
    }

    // 如果没有勾选保存邮箱，清空验证码
    if (!this.verifySaveEmail) {
      this.verifySaveCode = ''
    } else {
      if (!this.verifySaveCode) {
        this.$message.error('请输入验证码')

        return
      }
    }

    payOrder
      .invoice(
        this.invoiceType,
        this.defaultData.payOrderId,
        this.payerEmail,
        this.taxpayerIdentityNumber,
        this.verifySaveCode
      )
      .then(() => {
        if (this.verifySaveEmail) {
          // 同步用户的邮箱
          this.setStateData({
            accountEmail: this.payerEmail,
          })
        }

        this.beforeClose()
        this.$emit('visibleChange', false)
        this.$emit('submitHandler')
        this.$message.success('提交成功')
      })
  }

  private beforeClose() {
    this.invoiceType = 1
    this.payerEmail = ''
    this.taxpayerIdentityNumber = ''
    this.$emit('visibleChange', false)
  }

  private sendVerifyCode() {
    const RE_EMAIL = /[a-zA-Z0-9]{1,10}@[a-zA-Z0-9\\-]{1,50}\.[a-zA-Z0-9]{1,5}/

    if (!this.payerEmail) {
      this.$message.error('请输入接收人电子邮箱')

      return
    } else if (!RE_EMAIL.test(this.payerEmail)) {
      this.$message.error('请输入正确的接收人电子邮箱')

      return
    }

    if (this.verifyBtnMsg !== '获取验证码') return

    this.verifyBtnMsg = '请求中'

    service({
      url: '/seal/rest/account/simpleSendMobileCode',
      method: 'POST',
    }).then(res => {
      let time = 90

      this.timer = setInterval(() => {
        if (time === 0) {
          clearInterval(this.timer)
          this.verifyBtnMsg = '获取验证码'

          return
        }

        this.verifyBtnMsg = `${time}s后重新获取`
        time--
      }, 1e3)
    })
  }

  @Watch('visible')
  visibleHandler(val: boolean) {
    if (val) {
      if (this.defaultData.invoiceStatus === invoice.invoiced) {
        // 已开票
        this.invoiceType = this.defaultData.invoiceType
        this.payerEmail = this.defaultData.payerEmail
        this.taxpayerIdentityNumber = this.defaultData.taxpayerIdentityNumber
      } else {
        // 在开票时 如果用户有邮箱则回显用户自己的邮箱
        this.payerEmail = this.email
      }
    } else {
      if (this.timer) {
        clearInterval(this.timer)
      }
      // 重置保存到邮箱相关字段
      this.verifyBtnMsg = '获取验证码'
      this.verifySaveEmail = false
    }
  }

  @Emit('visibleChange')
  private visibleChange(val: boolean) {
    return val
  }
}
